package com.kuang.dao.impl;

import com.kuang.dao.UserDao;
import com.kuang.pojo.User;
import com.kuang.utils.BaseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class UserDaoImpl implements UserDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public User saveUser(User user) {

        String sql = "insert into user (email, name, password) values (?, ?, ?)";

        // 对密码进行加密
        Object passwd =  BaseUtils.encryptionMD5(user.getPassword(), user.getEmail());

        jdbcTemplate.update(sql, user.getEmail(), user.getName(), passwd.toString());
        return user;
    }

    @Override
    public User getUserByEmail(String email) {

        String sql = "select * from user where email=?";

        try {
            Map<String, Object> map = jdbcTemplate.queryForMap(sql, email);
            User user = new User();
            user.setEmail((String) map.get("email"));
            user.setPassword((String) map.get("password"));
            return user;
        } catch (EmptyResultDataAccessException e) {
            // 没有查询到用户
            return null;
        }
    }
}
